<template>
  <view v-if="!isLoading" class="container" :style="appThemeStyle">
    <view class="header" style="height: 180rpx; padding: 0">
      <!-- 订单状态  待处理 售后中 售后完成-->
      <view class="order-status">
        <view class="status-text">
          <text>{{ order.state_text || "订单状态" }}</text>
        </view>
      </view>
      <!-- 下一步操作 -->
      <view class="next-action">
        <!--        <view class="action-btn mr20r">-->
        <!--          修改订单-->
        <!--        </view>-->
        <view
          @click="onOrderCancel"
          class="action-btn"
          v-if="info.orderStatus == 1 && info.saleStatus == 0"
        >
          取消订单
        </view>

        <view class="action-btn" v-if="info.saleStatus == 1">待售后</view>
        <view class="action-btn" v-if="info.saleStatus == 2">售后中</view>
        <view class="action-btn" v-if="info.saleStatus == 3">售后完成</view>
      </view>
    </view>

    <view class="card-area">
      <!-- 实物订单 -->
      <block>
        <!-- 快递配送：配送地址 -->
        <view class="delivery-address i-card">
          <div class="f ac xb">
            <view class="link-man f1">
              <text class="name">{{ form.consigneeName || "姓名" }}</text>
              <text class="phone">{{ form.consigneePhone || "联系方式" }}</text>
            </view>
            <!-- <div @click="show2 = true">修改地址</div> -->
          </div>
          <view class="address">
            <text
              class="region"
              v-for="(region, idx) in order.address.region"
              :key="idx"
            >
              {{ region || "省市区" }}
            </text>
            <text class="detail">
              {{ form.consigneeAddress }}{{ form.addressDetailed }}
            </text>
          </view>
        </view>
      </block>

      <!-- 物流信息 -->
      <view
        class="express i-card"
        @click="handleTargetExpress(info.expressType)"
      >
        <view v-if="false" class="main">
          <view class="info-item">
            <view class="item-content">
              <text>订单已拆分多个包裹发货</text>
            </view>
          </view>
          <view class="info-item">
            <view class="item-content">
              <text>已发货{{ order.delivery.length }}个包裹</text>
            </view>
          </view>
        </view>
        <view v-else class="main">
          <view class="info-item">
            <view class="item-lable">物流公司</view>
            <view class="item-content">
              <text>
                {{ info.expressType == 2 ? "顺丰" : "圆通" }}
              </text>
            </view>
          </view>
          <view class="info-item">
            <view class="item-lable">物流单号</view>
            <view class="item-content">
              <text>
                {{ info.waybillNo }}
              </text>
              <view
                v-if="order.delivery[0].express_no"
                class="act-copy"
                @click.stop="handleCopy(order.delivery[0].express_no)"
              >
                <text>复制</text>
              </view>
            </view>
          </view>
        </view>
        <view class="right-arrow">
          <text class="iconfont icon-arrow-right"></text>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="goods-list i-card">
        <view class="goods-item" v-for="(goods, idx) in goodsList" :key="idx">
          <view class="goods-main" @click="handleTargetGoods(goods.goodsId)">
            <!-- 商品图片 -->
            <view class="goods-image">
              <image
                class="image"
                :src="goods.goods_image"
                mode="scaleToFill"
              ></image>
            </view>
            <!-- 商品信息 -->
            <view class="goods-content">
              <view class="goods-title">
                <text class="twoline-hide">
                  {{ goods.title || "商品名称" }}
                </text>
              </view>
              <view class="goods-props clearfix">
                <div class="goods-props-item">分类：{{ goods.name }}</div>
              </view>
            </view>
            <!-- 交易信息 -->
            <view class="goods-trade">
              <view class="goods-price">
                <text class="unit">￥</text>
                <text class="value">{{ goods.price }}</text>
              </view>
              <view class="goods-num">
                <text>×{{ goods.num }}</text>
              </view>
            </view>
          </view>
          <!-- 切尔奇翁 -->
          <!-- 商品售后 -->
          <view class="order-total">
            <text>共{{ goods.num }}件商品，总金额</text>
            <text class="unit">￥</text>
            <text class="money">{{ goods.price + Number(info.mailPay) }}</text>
          </view>
          <!-- <view style="display: flex; justify-content: end; padding: 10px 0">
            <u-button  type="primary" @click="handleTargetGoods(goods.goodsId)">修改订单</u-button>
          </view> -->
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="order-info i-card">
        <view class="info-item">
          <view class="item-lable">订单编号</view>
          <view class="item-content">
            <text>{{ info.orderCode }}</text>
            <!-- <view class="act-copy" @click="handleCopy(order.order_no)">
              <text>复制</text>
            </view> -->
          </view>
        </view>
        <view class="info-item">
          <view class="item-lable">下单时间</view>
          <view class="item-content">
            <text>{{ info.createTime }}</text>
          </view>
        </view>
        <!-- <view class="info-item">
          <view class="item-lable">买家留言</view>
          <view class="item-content">
            <text>{{ order.buyer_remark ? order.buyer_remark : "--" }}</text>
          </view>
        </view> -->
      </view>

      <view style="padding: 20rpx">
        <u-button
          @click="copy"
          shape="circle"
          text="提取订单信息"
          color="linear-gradient(to right,#ababab, #c7a157)"
        ></u-button>
      </view>

      <!-- 结算信息 -->
      <!-- <view class="trade-info i-card">
        <view class="info-item">
          <view class="item-lable">订单金额</view>
          <view class="item-content">
            <text>￥{{ order.total_price }}</text>
          </view>
        </view>
        <view v-if="order.coupon_money > 0" class="info-item">
          <view class="item-lable">优惠券抵扣</view>
          <view class="item-content">
            <text>-￥{{ order.coupon_money }}</text>
          </view>
        </view>
        <view v-if="order.points_money > 0" class="info-item">
          <view class="item-lable">{{ setting.points_name }}抵扣</view>
          <view class="item-content">
            <text>-￥{{ order.points_money }}</text>
          </view>
        </view>
        <view class="info-item">
          <view class="item-lable">运费</view>
          <view class="item-content">
            <text>+￥{{ order.express_price }}</text>
          </view>
        </view>

        <view class="divider"></view>
        <view class="trade-total">
          <text class="lable">实付款</text>
          <view class="goods-price">
            <text class="unit">￥</text>
            <text class="value">{{ order.pay_price }}</text>
          </view>
        </view>
      </view> -->
    </view>

    <!-- 底部操作按钮 -->
    <view
      v-if="order.order_status != OrderStatusEnum.CANCELLED.value"
      class="footer-fixed"
    >
      <view class="btn-wrapper">
        <!-- 未支付取消订单 -->
        <block v-if="order.pay_status == PayStatusEnum.PENDING.value">
          <view class="btn-item" @click="onCancel(order.order_id)">取消</view>
        </block>
        <!-- 已支付进行中的订单 -->
        <block v-if="order.order_status != OrderStatusEnum.APPLY_CANCEL.value">
          <block
            v-if="
              order.pay_status == PayStatusEnum.SUCCESS.value &&
              order.delivery_status == DeliveryStatusEnum.NOT_DELIVERED.value
            "
          >
            <view class="btn-item" @click="onCancel(order.order_id)">
              申请取消
            </view>
          </block>
        </block>
        <!-- 已申请取消 -->
        <view v-else class="f-28 col-8">取消申请中</view>
        <!-- 未支付的订单 -->
        <block v-if="order.pay_status == PayStatusEnum.PENDING.value">
          <view class="btn-item active" @click="onPay(order.order_id)">
            去支付
          </view>
        </block>
        <!-- 确认收货 -->
        <block
          v-if="
            order.delivery_status == DeliveryStatusEnum.DELIVERED.value &&
            order.receipt_status == ReceiptStatusEnum.NOT_RECEIVED.value
          "
        >
          <view class="btn-item active" @click="onReceipt(order.order_id)">
            确认收货
          </view>
        </block>
        <!-- 订单评价 -->
        <block
          v-if="
            order.order_status == OrderStatusEnum.COMPLETED.value &&
            order.is_comment == 0
          "
        >
          <view class="btn-item" @click="handleTargetComment(order.order_id)">
            评价
          </view>
        </block>
      </view>
    </view>
    <u-popup :show="show" @close="show = false">
      <div style="padding: 30rpx">
        <u-steps dot :current="statusList.length" direction="column">
          <u-steps-item
            v-for="(i, index) in statusList"
            :key="index"
            :title="i.processInfo"
            :desc="i.processTime"
          ></u-steps-item>
        </u-steps>
      </div>
    </u-popup>
    <u-popup :show="show2" @close="show2 = false">
      <view class="form-wrapper" style="padding: 30rpx">
        <u--textarea
          @confirm="handleAddress"
          @blur="handleAddress"
          v-model="addressValue"
          placeholder="粘贴收货地址到此处，将自动识别姓名、电话、地址"
        ></u--textarea>
        <u-form :model="form" ref="uForm" label-width="140rpx" :rules="rules">
          <u-form-item label="收货人" prop="consigneeName" borderBottom>
            <u-input
              v-model="form.consigneeName"
              border="none"
              placeholder="请输入收货人姓名"
            />
          </u-form-item>
          <u-form-item label="手机号码" prop="consigneePhone" borderBottom>
            <u-input
              v-model="form.consigneePhone"
              border="none"
              placeholder="请输入收货人手机号"
            />
          </u-form-item>
          <u-form-item label="所在地区" prop="consigneeAddress" borderBottom>
            <div
              @click="visible = true"
              :class="{ ga6aab6: form.consigneeAddress == '' }"
            >
              {{ form.consigneeAddress || "请选择" }}
            </div>
          </u-form-item>
          <u-form-item label="详细地址" prop="addressDetailed" borderBottom>
            <u-input
              v-model="form.addressDetailed"
              border="none"
              placeholder="街道门牌、楼层等信息"
            />
          </u-form-item>
          <div class="mt20r">
            <u-button type="primary" @click="handleSubmit">保存</u-button>
          </div>
        </u-form>
      </view>
    </u-popup>
    <cityPicker
      :column="column"
      :default-value="defaultValue"
      :mask-close-able="maskCloseAble"
      @confirm="confirm"
      @cancel="visible = false"
      :visible="visible"
    />
  </view>
</template>

<script>
import cityPicker from "@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker";

import {
  getOrderDetail,
  cancelOrder,
  changeAddress,
  getProcess,
} from "../../api/shoppingCart";
import { AddressParse } from "../../utils/addressParseBundle";
import { getuserInfo} from "../../api/old";
const rules = {
  consigneeName: [
    {
      required: true,
      message: "请输入姓名",
      trigger: ["blur", "change"],
    },
  ],
  consigneePhone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: ["blur", "change"],
    },
    {
      // 自定义验证函数
      validator: (rule, value, callback) => {
        // 返回true表示校验通过，返回false表示不通过
        return isMobile(value);
      },
      message: "手机号码不正确",
      // 触发器可以同时用blur和change
      trigger: ["blur", "change"],
    },
  ],
  consigneeAddress: [
    {
      required: true,
      message: "请选择省市区",
      trigger: ["blur", "change"],
    },
  ],
  addressDetailed: [
    {
      required: true,
      message: "请输入详细地址",
      trigger: ["blur", "change"],
    },
  ],
};

export default {
  data() {
    return {
      userInfo:{},
      statusList: {},
      info: {},
      // 当前订单ID
      orderId: null,
      // 加载中
      isLoading: false,
      // 当前订单详情
      order: {},
      // 当前设置
      setting: {},
      // 控制onShow事件是否刷新订单信息
      canReset: false,
      show: false,
      show2: false,
      goodsList: [],
      rules,
      saleType: "",
      form: {
        consigneeName: "",
        consigneePhone: "",
        addressDetailed: "",
        consigneeAddress: "",
        address: "",
      },
      addressValue: "",
      visible: false,
      column: 3,
      defaultValue: "",
      maskCloseAble: true,
    };
  },
  components: { cityPicker },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(val) {
    // 当前订单ID
    this.orderId = val.orderId;
    console.log(val, "asddasdasdas");
    this.saleType = val.saleType;
    getOrderDetail(val.orderCode).then(({ data }) => {
      this.goodsList = data.orderDetails;
      this.form = data.orderConsignee;
      this.info = data;
      console.log(this.form, "formform");
    });
    getuserInfo().then(res=>{
      this.userInfo = res.data;
    });

    // 获取当前订单信息
    // this.getOrderDetail()
    // // 注册全局事件订阅: 是否刷新当前订单数据
    // uni.$on('syncRefresh', (val, isCur) => {
    //   if (!isCur) {
    //     this.canReset = val
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.canReset && this.getOrderDetail()
    // this.canReset = false
  },

  methods: {
    copy() {

      // 使用map方法获取所有title组成的数组
      let titles = this.info.orderDetails.map((item) => item.title);

      // 使用join方法将数组中的title拼接成一个字符串
      let name = titles.join(",");
      let type = this.userInfo.remark == 1 ? '零售': this.userInfo.remark == 2 ? '代理':'客服'
      let str = `下单时间：${this.info.createTime}\n下单人：${this.userInfo.userName}(${type})\n姓名：${this.info.orderConsignee.consigneeName}\n电话：${this.info.orderConsignee.consigneePhone}\n本单产品：${name}\n快递单号：${this.info.waybillNo}\n问题原因：\n售后要求：\n寄回单号：`;
      uni.setClipboardData({
        data: str,
        success: function () {
          uni.showToast({
            title: "复制成功",
            icon: "success",
            duration: 1500,
          });
        },
      });
    },
    // 取消订单
    onOrderCancel() {
      cancelOrder(this.orderId).then((res) => {
        console.log(res.code, "code");
        if (res.code == 200) {
          uni.showToast({
            title: "提交成功",
            icon: "none",
            duration: 1500,
            success: () => {
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            },
          });
        }
      });
    },
    handleAddress() {
      const result = AddressParse.parse(this.addressValue);
      this.$set(this.form, "consigneeName", result[0].name);
      this.$set(this.form, "consigneePhone", result[0].phone);
      this.$set(
        this.form,
        "consigneeAddress",
        `${result[0].province}${result[0].city}${result[0].area}`
      );
      this.$set(this.form, "addressDetailed", result[0].details);
    },
    confirm(val) {
      this.form.consigneeAddress = val.name;
      this.form.address =
        val.provinceName + "," + val.cityName + "," + val.areaName;
      console.log(this.str);
      this.visible = false;
    },
    handleSubmit() {
      changeAddress(this.form).then((res) => {
        uni.showToast({
          title: "修改成功",
          icon: "none",
          duration: 1000,
          success: () => {
            setTimeout(() => {
              // this.goCart();
            }, 1000);
          },
        });
      });
      this.show2 = false;
    },
    // 获取当前订单信息
    getOrderDetail(canReset = false) {
      const app = this;
      app.isLoading = true;
      OrderApi.detail(app.orderId).then((result) => {
        app.order = result.data.order;
        app.setting = result.data.setting;
        app.isLoading = false;
      });
      // 相应全局事件订阅: 刷新上级页面数据
      canReset && uni.$emit("syncRefresh", true, true);
    },

    // 复制指定内容
    handleCopy(value) {
      const app = this;
      uni.setClipboardData({
        data: value,
        success: () => app.$toast("复制成功"),
        fail: ({ errMsg }) => app.$toast("复制失败 " + errMsg),
      });
    },

    // 跳转到物流跟踪页面
    handleTargetExpress() {
      getProcess(this.orderId).then((res) => {
        if (res.code == 200) {
          this.show = true;
          this.statusList = res.data.data;
        } else {
          this.$toast(res.data.message);
        }
        console.log(res, "ssssssss");
      });
      // this.$navTo('pages/order/express/index', {orderId: this.orderId})
    },

    // 跳转到商品详情页面
    handleTargetGoods(Id) {
      // this.$navTo("pages/goods/detail", { Id:Id,isUpdate:'1' });
    },

    // 跳转到申请售后页面
    handleApplyRefund(orderGoodsId) {
      this.$navTo("pages/refund/apply", { orderGoodsId });
    },

    // 取消订单
    onCancel(orderId) {
      const app = this;
      uni.showModal({
        title: "友情提示",
        content: "确认要取消该订单吗？",
        success(o) {
          if (o.confirm) {
            OrderApi.cancel(orderId).then((result) => {
              // 显示成功信息
              app.$toast(result.message);
              setTimeout(() => {
                // 刷新当前订单数据
                app.getOrderDetail(true);
              }, 1500);
            });
          }
        },
      });
    },

    // 确认收货
    onReceipt(orderId) {
      const app = this;
      uni.showModal({
        title: "友情提示",
        content: "确认收到商品了吗？",
        success(o) {
          if (o.confirm) {
            OrderApi.receipt(orderId).then((result) => {
              // 显示成功信息
              app.$success(result.message);
              setTimeout(() => {
                // 刷新当前订单数据
                app.getOrderDetail(true);
              }, 1500);
            });
          }
        },
      });
    },

    // 点击去支付
    onPay(orderId) {
      this.$navTo("pages/checkout/cashier/index", { orderId });
    },

    // 跳转到订单评价页
    handleTargetComment(orderId) {
      this.$navTo("pages/order/comment/index", { orderId });
    },
  },
};
</script>

<style>
page {
  background: #f4f4f4;
}
</style>
<style lang="scss" scoped>
.container {
  // 设置ios刘海屏底部横线安全区域
  padding-bottom: calc(constant(safe-area-inset-bottom) + 106rpx + 6rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 106rpx + 6rpx);
}

// 页面顶部
.header {
  display: flex;
  justify-content: space-between;
  background-color: #e8c269;
  height: 280rpx;
  padding: 56rpx 30rpx 0 30rpx;

  .order-status {
    display: flex;
    align-items: center;
    height: 128rpx;

    .status-icon {
      width: 128rpx;
      height: 128rpx;

      .image {
        display: block;
        width: 100%;
        height: 100%;
      }
    }

    .status-text {
      padding-left: 20rpx;
      color: #fff;
      font-size: 38rpx;
      font-weight: bold;
    }
  }

  .next-action {
    display: flex;
    align-items: center;
    height: 128rpx;

    .action-btn {
      min-width: 152rpx;
      height: 56rpx;
      padding: 0 30rpx;
      background-color: #fff;
      border-radius: 28rpx;
      border-color: rgb(102, 102, 102);
      cursor: pointer;
      user-select: none;
      color: #c7a157;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

// 卡片区域
.card-area {
  margin-top: -50rpx;
}

// 通栏卡片
.i-card {
  background: #fff;
  padding: 24rpx 24rpx;
  width: 94%;
  box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
  margin: 0 auto 20rpx auto;
  border-radius: 20rpx;
}

// 收货地址
.delivery-address {
  .link-man {
    line-height: 46rpx;
    color: #333;

    .name {
      margin-right: 10rpx;
    }
  }

  .address {
    margin-top: 12rpx;
    color: #999;
    font-size: 24rpx;

    .detail {
      margin-left: 6rpx;
    }
  }
}

// 物流公司
.express {
  display: flex;
  align-items: center;

  .main {
    flex: 1;
  }

  .info-item {
    display: flex;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .item-lable {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #999;
      margin-right: 30rpx;
    }

    .item-content {
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 26rpx;
      color: #333;

      .act-copy {
        margin-left: 20rpx;
        padding: 2rpx 20rpx;
        font-size: 22rpx;
        color: #666;
        border: 1rpx solid #c1c1c1;
        border-radius: 16rpx;
      }
    }
  }

  // 右侧箭头
  .right-arrow {
    margin-left: 16rpx;
    font-size: 26rpx;
  }
}

// 商品列表
.goods-list {
  // 商品项
  .goods-item {
    margin-bottom: 40rpx;

    &:last-child {
      margin-bottom: 0;
    }

    // 商品信息
    .goods-main {
      display: flex;
    }

    // 商品图片
    .goods-image {
      width: 180rpx;
      height: 180rpx;

      .image {
        display: block;
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
    }

    // 商品内容
    .goods-content {
      flex: 1;
      padding-left: 16rpx;
      padding-top: 16rpx;

      .goods-title {
        font-size: 26rpx;
        max-height: 76rpx;
      }

      .goods-props {
        margin-top: 14rpx;
        color: #ababab;
        font-size: 24rpx;
        overflow: hidden;

        .goods-props-item {
          padding: 4rpx 16rpx;
          border-radius: 12rpx;
          background-color: #fcfcfc;
        }
      }
    }

    // 交易信息
    .goods-trade {
      padding-top: 16rpx;
      width: 150rpx;
      text-align: right;
      color: $uni-text-color-grey;
      font-size: 26rpx;

      .goods-price {
        vertical-align: bottom;
        margin-bottom: 16rpx;

        .unit {
          margin-right: -2rpx;
          font-size: 24rpx;
        }
      }
    }

    // 商品售后
    .goods-refund {
      display: flex;
      justify-content: flex-end;

      .stata-text {
        font-size: 24rpx;
        color: #999;
      }

      .action-btn {
        border-radius: 28rpx;
        padding: 8rpx 26rpx;
        font-size: 24rpx;
        color: #383838;
        border: 1rpx solid #a8a8a8;
      }
    }
  }
}

// 订单信息
.order-info {
  .info-item {
    display: flex;
    margin-bottom: 24rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .item-lable {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #999;
      margin-right: 30rpx;
    }

    .item-content {
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 26rpx;
      color: #333;

      .act-copy {
        margin-left: 20rpx;
        padding: 2rpx 20rpx;
        font-size: 22rpx;
        color: #666;
        border: 1rpx solid #c1c1c1;
        border-radius: 16rpx;
      }
    }
  }
}

// 交易信息
.trade-info {
  .info-item {
    display: flex;
    margin-bottom: 24rpx;

    .item-lable {
      font-size: 24rpx;
      color: #999;
      margin-right: 24rpx;
    }

    .item-content {
      flex: 1;
      font-size: 26rpx;
      color: #333;
      text-align: right;
    }
  }

  .divider {
    height: 1rpx;
    background: #f1f1f1;
    margin-bottom: 24rpx;
  }

  .trade-total {
    display: flex;
    justify-content: flex-end;

    .goods-price {
      margin-left: 12rpx;
      vertical-align: bottom;
      color: $main-bg;

      .unit {
        margin-right: -2rpx;
        font-size: 24rpx;
      }
    }
  }
}

// 底部操作栏
.footer-fixed {
  position: fixed;
  bottom: var(--window-bottom);
  left: 0;
  right: 0;
  z-index: 11;
  box-shadow: 0 -4rpx 40rpx 0 rgba(151, 151, 151, 0.24);
  background: #fff;

  // 设置ios刘海屏底部横线安全区域
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  .btn-wrapper {
    height: 106rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 30rpx;
  }

  .btn-item {
    min-width: 180rpx;
    border-radius: 30rpx;
    padding: 12rpx 26rpx;
    font-size: 28rpx;
    color: #383838;
    text-align: center;
    border: 1rpx solid #a8a8a8;
    margin-left: 24rpx;

    &.active {
      border: none;
      background: linear-gradient(to right, $main-bg, $main-bg2);
      color: $main-text;
    }
  }
}

// 订单合计
.order-total {
  font-size: 26rpx;
  vertical-align: bottom;
  text-align: right;
  height: 40rpx;
  margin-bottom: 30rpx;

  .unit {
    margin-left: 8rpx;
    margin-right: -2rpx;
    font-size: 26rpx;
  }

  .money {
    font-size: 28rpx;
  }
}
</style>
